import 'dart:async';

import 'package:flutter/material.dart';

class StreamBuilderDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return HomeWidget();
  }
}

class HomeWidget extends StatefulWidget {
  @override
  State createState() {
    return HomeState();
  }
}

class HomeState extends State<HomeWidget> {
  var index = 0;
  //创建StreamController
  var streamController;
  // 获取StreamSink用于发射事件
  StreamSink<String> get streamSink => streamController.sink;
  // 获取Stream用于监听
  Stream<String> get streamData => streamController.stream;

  void onFloatActionButtonPress() {
    index++;
    //发射一个事件.
    streamSink.add(index.toString());
  }

  @override
  void initState() {
    super.initState();
    streamController = StreamController<String>();
    streamSink.add("0");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('streamBuilder')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            StreamBuilder<String>(
              stream: streamData,
              builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
                return Text('Result: ${snapshot.data}');
              },
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: onFloatActionButtonPress,
        child: Icon(Icons.add),
      ),
    );
  }
}
